﻿CREATE PROCEDURE [dbo].[ShiftOutDocUpdate]
(--Расход по внутреннему перемещению
	@DocDate smalldatetime,
	@DocNumber varchar(20),
	@ShiftDepartmentId int,  --код подразделения, куда перемещяется товар
	@ParentId int,					 --идентификатор исходного документа
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50),
	@Original_Id int,
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @orgDocDate smalldatetime, @orgDocTypeId int

SET NOCOUNT ON

IF (@ShiftDepartmentId Is Null) OR (@DocDate Is Null) OR (@DocNumber Is Null)
OR (@Original_Id Is Null) OR (@Original_MD Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

SELECT @orgDocTypeId = DocTypeId, @orgDocDate = DocDate
FROM CA.Documents WHERE Id = @Original_Id AND MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF @orgDocTypeId <> 4
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Неправильный тип документа!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SET @DocDate = dbo.NormalizeDate(@DocDate)

IF @orgDocDate > @DocDate --новая дата МЕНЬШЕ чем старая
BEGIN
	IF EXISTS (
SELECT TOP (1) D.Id FROM CA.GoodsDocLines AS SL INNER JOIN
CA.GoodsDocLines AS DL ON SL.ReturnLineId = DL.Id INNER JOIN
CA.Documents AS D ON DL.DocId = D.Id AND D.DocDate > @DocDate
WHERE SL.DocId = @Original_Id
)
	BEGIN
		SELECT @intErrCode = 4, 
		@strMsg = 'Даты приходов товаров больше чем новая дата расхода!'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT

	SET NOCOUNT OFF;
UPDATE [CA].[Documents] SET 
[DocDate] = @DocDate, 
[DocNumber] = @DocNumber, 
ShiftDepartmentId = @ShiftDepartmentId,
ParentId = @ParentId, 
[Note] = @Note, [MD] = @MD, [MW] = @MW 
WHERE Id = @Original_Id AND MD = @Original_MD;
	
SELECT Id, DocTypeId, DocDate, DocNumber, 
ShiftDepartmentId, DepartmentUserId, ParentId, Note, MD, MW 
FROM CA.Documents WHERE (Id = @Original_Id)

RETURN 0



